//
//  AccountListViewController.m
//  quickBatchManager
//
//  Created by 王定波 on 15/10/10.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "AccountListViewController.h"

@interface AccountListViewController ()
{
    NSArray *datalist;
    AccountType accounttype;
    NSMutableDictionary *numDic;
}
@end

@implementation AccountListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)initData
{
    accounttype=AccountTypeClient;
    numDic=[[NSMutableDictionary alloc] init];
}

-(void)initUI
{
    [self addNavBack];
    UIColor *sbgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"beijingtur"]];
    [self.view setBackgroundColor:sbgColor];
    
    UIImage *image = _bg.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    _bg.image=image;
    
    _tableView.backgroundColor=[UIColor clearColor];
    
    self.view.frame=CGRectMake(0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT);
    
    [_kfbtn bk_whenTapped:^{
        [self setBtnSelected:AccountTypeClient];
        
    }];
    
    [_gysbtn bk_whenTapped:^{
        [self setBtnSelected:AccountTypeSupplier];
        
    }];
    
    [_dbbtn bk_whenTapped:^{
        [self setBtnSelected:AccountTypeAllocate];
        
    }];
    
    [_addBtn bk_whenTapped:^{
        NSMutableArray *navarray=[[NSMutableArray alloc] init];
        [navarray addObject:[self.splitViewController.viewControllers objectAtIndex:0] ];
        if(accounttype==AccountTypeSupplier)
        {
            
            EditSupplierViewController *handVc=[[EditSupplierViewController alloc] init];
            handVc.delegate=self;
            [navarray addObject:handVc];
        }
        else
        {
            
            AddClientController *handVc=[[AddClientController alloc] init];
            handVc.clientType=accounttype;
            handVc.delegate=self;
            [navarray addObject:handVc];
            
        }
        self.splitViewController.viewControllers=navarray;
    }];
    
    [_orderBtn bk_whenTapped:^{
        _orderBtn.selected=(!_orderBtn.isSelected);
        [self reloadData];
    }];
    
    
    
    [self setBtnSelected:AccountTypeClient];
    [self addTextFieldChange:_nameField];
    
   
    
    
}


-(void)setBtnSelected:(AccountType)type
{
    
    accounttype=type;
    _kfbtn.selected=(type==AccountTypeClient?YES:NO);
    _gysbtn.selected=(type==AccountTypeSupplier?YES:NO);
    _dbbtn.selected=(type==AccountTypeAllocate?YES:NO);
    
    if(type==AccountTypeSupplier)
    {
        _tab1.text=@"姓名";
        _tab2.text=@"数量";
    }
    else
    {
        _tab1.text=@"区域";
        _tab2.text=@"姓名";
    }
    

    self.splitViewController.viewControllers=@[[self.splitViewController.viewControllers objectAtIndex:0] ];
    [self reloadData];
    
}


-(void)back
{
    [self.splitViewController dismissViewControllerAnimated:YES completion:nil];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return datalist.count;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    AccountDescListViewController *handVc=[[AccountDescListViewController alloc] init];
    
    
    if(accounttype!=AccountTypeSupplier)
    {
        ClientModel *data=[datalist objectAtIndex:indexPath.row];
        handVc.client=data;
    }
    else
    {
        SupplierModel *data=[datalist objectAtIndex:indexPath.row];
        handVc.supplier=data;
    }
    
    handVc.accountType=accounttype;
    BaseNavigationController *nav=[[BaseNavigationController alloc] initWithRootViewController:handVc];
    [self.splitViewController presentViewController:nav animated:YES completion:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *reuseIdetify = @"AccountListViewCell";
    AccountListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
    if(!cell){
        
        
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"AccountListViewCell" owner:self options:nil];
        for(id oneObject in nib){
            if([oneObject isKindOfClass:[AccountListViewCell class]]){
                cell = (AccountListViewCell *) oneObject;
                
            }
        }
        
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor clearColor];
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
    NSString *key;
    

    
    
    if(accounttype!=AccountTypeSupplier)
    {
        
        ClientModel *data=[datalist objectAtIndex:indexPath.row];
        key=[ToolUtils numberToStr:data.clientId];
        cell.label1.text=data.area;
        cell.label2.text=data.clientName;
        cell.label3.text=[numDic objectForKey:key];
        
        
        [cell.editBtn bk_whenTapped:^{
            NSMutableArray *navarray=[[NSMutableArray alloc] init];
            [navarray addObject:[self.splitViewController.viewControllers objectAtIndex:0] ];
            
            AddClientController *handVc=[[AddClientController alloc] init];
            handVc.clientType=accounttype;
            handVc.client=data;
            handVc.delegate=self;
            [navarray addObject:handVc];
            self.splitViewController.viewControllers=navarray;
            
        }];
        
        
        
    }
    else
    {
        SupplierModel *data=[datalist objectAtIndex:indexPath.row];
        key=[ToolUtils numberToStr:data.supplierId];
        cell.label1.text=data.contactName;
        cell.label2.text=[ToolUtils numberToStr:[AppService getSupplierTotalNumberById:data.supplierId]];
        cell.label3.text=[numDic objectForKey:key];
        
        
        [cell.editBtn bk_whenTapped:^{
            NSMutableArray *navarray=[[NSMutableArray alloc] init];
            [navarray addObject:[self.splitViewController.viewControllers objectAtIndex:0] ];
            
            EditSupplierViewController *handVc=[[EditSupplierViewController alloc] init];
            handVc.supplier=data;
            handVc.delegate=self;
            [navarray addObject:handVc];
            self.splitViewController.viewControllers=navarray;
            
        }];
        
    }
    

    
    return cell;
    
    
}

-(void)reloadData
{
    if(accounttype==AccountTypeClient)
    {
        datalist=[ClientModel searchWithWhere:[NSString stringWithFormat:@"clientType=0 and clientName Like '%%%@%%'",_nameField.text]];
    }
    else if(accounttype==AccountTypeSupplier)
    {
        datalist=[SupplierModel searchWithWhere:[NSString stringWithFormat:@"contactName Like '%%%@%%'",_nameField.text]];
    }
    else  datalist=[ClientModel searchWithWhere:[NSString stringWithFormat:@"clientType=1 and clientName Like '%%%@%%'",_nameField.text]];
    
    
    NSString *st=[NSString stringWithFormat:@"总欠款 %0.1f元",[AppService getAmountByUserIdAndType:0 andType:accounttype]];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:st];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4,st.length-5)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:24] range:NSMakeRange(4,st.length-5)];
   
     _totalAmountLabel.attributedText = str;
    
    if(accounttype==AccountTypeSupplier)
    {
        [numDic removeAllObjects];
        for (SupplierModel *data in datalist) {
            [numDic setObject:[ToolUtils priceToStr:[AppService getAmountByUserIdAndType:data.supplierId andType:accounttype]] forKey:[ToolUtils numberToStr:data.supplierId]];
        }
    }
    else
    {
        [numDic removeAllObjects];
        for (ClientModel *data in datalist) {
            [numDic setObject:[ToolUtils priceToStr:[AppService getAmountByUserIdAndType:data.clientId andType:accounttype]] forKey:[ToolUtils numberToStr:data.clientId]];
        }
    }
    
    
   
    
    datalist=[datalist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
         NSString *p1,*p2;
         if(accounttype==AccountTypeSupplier)
         {
             p1=[ToolUtils numberToStr:((SupplierModel*)obj1).supplierId];
             p2=[ToolUtils numberToStr:((SupplierModel*)obj2).supplierId];
         }
        else
        {
            p1=[ToolUtils numberToStr:((ClientModel*)obj1).clientId];
            p2=[ToolUtils numberToStr:((ClientModel*)obj2).clientId];
        }
        
        if ([[numDic objectForKey:p1] doubleValue] > [[numDic objectForKey:p2] doubleValue]) {
            if(_orderBtn.isSelected)
            return (NSComparisonResult)NSOrderedDescending;
            else  return (NSComparisonResult)NSOrderedAscending;
        }
        
        if ([[numDic objectForKey:p1] doubleValue] < [[numDic objectForKey:p2] doubleValue]) {
            if(!_orderBtn.isSelected)
                return (NSComparisonResult)NSOrderedDescending;
            else  return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    
    
    [_tableView reloadData];
}

-(void)didChange:(ChangeType)type andData:(id)data
{
    [self reloadData];
}


-(void)textFieldChanged:(id)sender
{
    [self reloadData];
}
@end
